<script setup lang='ts'>
import { onMounted, ref, reactive ,markRaw} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Timer, Check, Close, Delete } from '@element-plus/icons-vue'
import http from '../../api/http'
import type { IaddGoods, IgoodS } from '@/types/good'
import Create from "@/views/goods/add.vue"
import Edit from "@/views/goods/edit.vue"
import { imgBaseURL,apiBaseURL } from '@/api/baseURL'
//#region  列表分页查询相关
const loading=ref(false)
const autoHide =ref(false)
const tableData: IgoodS[] = reactive([])
const likename = ref('')
const page = ref(1)
const size = ref(5)
const total = ref(0)
//查询用户数据
const getUsers = () => {
        loading.value = true;

    http.getList<IgoodS>('Goods/page', { page: page.value, size: size.value, name: likename.value })
        .then(res => {
            total.value = res.count
            tableData.length = 0
            tableData.push(...res.data)
                setTimeout(() => {
                    loading.value = false;
                }, 200);
                console.log(res.data)
                console.log(tableData.values)

        }).catch(err => {
            console.log('err: ', err);
        })
}
//每页数量的改变事件
const handleSizeChange = (val: number) => {
    size.value = val
    getUsers()
}
//翻页
const handleCurrentChange = (val: number) => {
    page.value = val
    getUsers()
}
//#endregion

//#region  添加
const createDialogVisible = ref(false)
const create = () => {
    //弹出添加框
   
    createDialogVisible.value = true
}
//#endregion 

//#region  修改
const formData = ref({
    "gid": 1,
      "name": "奈雪早餐",
      "content": "购买三明治,享早餐指定饮品半价",
      "images": "/static/picture/goods/fda6dd99c83af02353.jpg",
      "use_Spec": false,
      "use_Property": false,
      "unit": "件",
      "price": 18.5,
      "sales": 0,
      "sort": 0,
      "gtid": 1,
      "on_sale": true,
      "typeName": "奈雪早餐",
      "goodPropertyKey": [
        {
            "gpkid": 1,
          "name": "温度",
          "gskid": 2,
          "goodPropertyValue": [
            {
              "gpvid": 1,
              "is_Default": true,
              "gsvid": 30,
              "code": "",
              "value": "标准冰"
            },
            {
              "gpvid": 2,
              "is_Default": false,
              "gsvid": 31,
              "code": "",
              "value": "去冰"
            }
          ]
        }
      
      ]
})
const editDialogVisible = ref(false)
const edit = (row: IaddGoods) => {
   //规格
   
      let data = JSON.parse(JSON.stringify(row));
         
            let property = [
                {
                    gskid: 1,  //规格 主键表  GoodSpecKey  id
                    goodsPropertyValue: [],
                    checked: false,
                     name:'食品口味'
                },
                {
                    gskid: 2,
                    goodsPropertyValue: [],
                    checked: false,
                    name:'净含量'
                },
                {
                    gskid: 3,
                    goodsPropertyValue: [],
                    checked: false,
                     name:'重量'
                }
            ]
            data.goodPropertyKey.forEach(key => {
                let pp = property.filter(v => v.gskid == key.gskid)[0];
                pp.checked = true;
                key.goodPropertyValue.forEach(v => {
                    pp.goodsPropertyValue.push(v.gsvid);
                })
            })

            data.goodsPropertyKey = property;

    formData.value = data
    //弹出修改框
    editDialogVisible.value = true

}
const search=reactive({name:""})
//#endregion 
const highlight=(v)=>{
 return v.replace(search.name, '<span class="highlight">' +search.name + '</span>')


}
//#region 单个删除
const del = (id: number) => {
    http.delete('Goods',{id:id})
        .then(res => {
            if (res.code == '1') {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
                //刷新
                getUsers();
            }
            else {
                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
            }
        })

}
//#endregion

//#region 批量删除
const multipleSelection = ref<IgoodS[]>([])  //选中的值 全部值
const handleSelectionChange = (val: IgoodS[]) => {
    multipleSelection.value = val
    //console.log('multipleSelection.value: ', multipleSelection.value)
}
const deleteRange = () => {
    if (multipleSelection.value.length > 0) {
        let ids: number[] = []
        let names: string[] = []
        multipleSelection.value.forEach(v => {
            ids.push(v.gid)
            names.push(v.name)
        })
        ElMessageBox.confirm(
            '确实删除【' + names + '】?',
            '',
            {
                type: 'warning',
                icon: markRaw(Delete),
            }
        ).then(() => {
            //提交删除
            http.delete('Goods/DeleteBatch',ids)
                .then(res => {
                    if (res.code == '1') {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        //刷新
                        getUsers();
                    }
                    else {
                        ElMessage({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                })

        })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消删除!',
                })
            })

    } else {
        ElMessage('请选择需要删除的商品！')
    }
}
//#endregion

//#region  组件挂载（初始化）
onMounted(() => {
    getUsers();
})
//#endregion 

</script>

<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <!-- 头部 操作 -->
        <template #header>
            <div class="card-header">
                <el-button type="success" @click="create()">添加商品</el-button>
                <el-button type="warning" @click="deleteRange">批量删除</el-button>

                <el-input v-model="likename" style="max-width: 300px;margin-left: 12px;" placeholder="请输入查询条件"
                    class="input-with-select">
                    <template #append>
                        <el-button type="primary" @click="getUsers()">查询</el-button>
                    </template>
                </el-input>
            </div>
        </template>
        <!-- 数据表 -->
        <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
           <el-table-column type="expand">
                    <template #default="scope">
                        <el-col :span="8" v-for="item in scope.row.goodPropertyKey" :key="item.gpkid">
                            {{ item.name }}
                            <ul>
                                <li v-for="pp in item.goodPropertyValue" :key="pp.gpvid">
                                    {{ pp.value }}</li>
                            </ul>
                        </el-col>
                    </template>
                </el-table-column>

                <el-table-column type="selection" width="55">
                </el-table-column>

                <el-table-column prop="gid" label="编号" width="55">
                </el-table-column>

                <el-table-column prop="images" label="图片">
                    <template #default="{ row }">
                        <el-avatar :src="imgBaseURL + row.images"></el-avatar>
                    </template>
                </el-table-column>

                <el-table-column prop="name" label="商品">
                    <template #default="{ row }">
                        <div v-html="highlight(row.name)"></div>
                    </template>
                </el-table-column>

                <el-table-column prop="content" label="描述" show-overflow-tooltip>
                    <template #default="{ row }">
                        <div v-html="highlight(row.content)"></div>
                    </template>
                </el-table-column>

                <el-table-column prop="price" label="价格">
                </el-table-column>

                <el-table-column prop="typeName" label="类型">
                </el-table-column>


                <el-table-column prop="use_Property" label="规格">
                    <template #default="{ row }">
                        <!-- @change="" -->
                        <el-switch v-model="row.use_Property" :active-value="true" :inactive-value="false">
                        </el-switch>

                    </template>
                </el-table-column>


           
            <el-table-column label="操作" fixed="right" width="160">

                <template #default="{ row }">
                    <el-button type="warning" size="small" @click="edit(row)">修改</el-button>
                    <el-popconfirm width="220" :title="'确定删除【' + row.name + '】?'" @confirm="del(row.gid)">
                        <template #reference>
                            <el-button size="small" type="danger">删除</el-button>
                        </template>
                        <template #actions="{ confirm, cancel }">
                            <el-button size="small" @click="cancel">取消</el-button>
                            <el-button type="primary" size="small" @click="confirm">
                                确定
                            </el-button>
                        </template>
                    </el-popconfirm>

                </template>

            </el-table-column>
        </el-table>
        <!-- 底部 分页 -->
        <template #footer>
            <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[5, 10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </template>
    </el-card>

    <!-- 新增、修改 弹窗组件 -->
    <Create v-model="createDialogVisible" @refresh="getUsers"></Create>
    <Edit v-model="editDialogVisible" :formData="formData" @refresh="getUsers"></Edit>

</template>


<style scoped>
.highlight {
    font-weight: 600;
    font-size: 16px;
    color: #ffffff;
    animation: glow 666ms infinite alternate;
}

@keyframes glow {
    form {
        text-shadow:
            0 0 10px #1877f2,
            0 0 20px #1459b3,
            0 0 30px #179bff;
    }


    to {
        text-shadow:
            0 0 5px #1877f2,
            0 0 10px #1459b3,
            0 0 15px #179bff;
    }
}

.demo-form-inline .el-form-item {
    margin-bottom: 0px;
}


</style>